//
//  UIImage+PLUtility.m
//
//  Created by KimmanYip on 2017/9/8.
//
//

#import "UIImage+PLExtension.h"

@implementation UIImage(PLExtension)

+ (UIImage *)pl_imageNamedWithoutCache:(NSString *)name {
    if (name && name.length > 0) {
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:name ofType:@"png"];
        if (!imagePath) {
            imagePath = [[NSBundle mainBundle] pathForResource:name ofType:@"jpg"];
        }
        return [[UIImage alloc] initWithContentsOfFile:imagePath];
    }
    return nil;
}

/** 根据颜色返回图片 */
+ (UIImage *)pl_imageWithColor:(UIColor*)color {
    return [self pl_imageWithColor:color size:CGSizeMake(1.0f, 1.0f)];
}

+ (UIImage *)pl_imageWithColor:(UIColor*)color size:(CGSize)size {
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

/** 将方形图片裁剪为带弧度的图片 */
- (UIImage *)pl_imageByClipWithCornerRadius:(CGFloat) cornerRadius {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0);
    
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    UIBezierPath* path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
    [path addClip];
    
    [self drawAtPoint:CGPointZero];
    UIImage* newImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImg;
}

/** 将方形图片裁剪为圆形图片 */
- (UIImage *)pl_imageByOvalClip {
    //1.根据图片尺寸获得图形上下文
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0);
    
    //2.设置裁剪区域
    UIBezierPath* path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
    [path addClip];
    
    //3.绘制新图片
    [self drawAtPoint:CGPointZero];
    UIImage* newImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImg;
}

- (UIImage *)pl_imageWithBorderWidth:(CGFloat)border borderColor:(UIColor *)color {
    //1.根据图片尺寸获得图形上下文
    CGSize size = CGSizeMake(self.size.width + border * 2, self.size.height + border * 2);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    
    //2.绘制边框
    UIBezierPath* path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, size.width, size.height)];
    [color set];
    [path fill];
    
    //3.绘制新图片
    [self drawAtPoint:CGPointMake(border, border)];
    UIImage* newImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImg;
}

/// 将背景图片和前景图片合成为一张图片
+ (UIImage *)pl_composeImageWithBackImage:(UIImage *)backImage foreImage:  (UIImage *)foreImage size:(CGFloat)sizeWH {
    CGSize size = [backImage size];
    
    UIGraphicsBeginImageContext(size);
    
    [backImage drawInRect : CGRectMake(0, 0, size.width, size.height)];
    
    CGFloat w = sizeWH;
    CGFloat h = sizeWH;
    CGFloat x = (size.width - w) * 0.5;
    CGFloat y = (size.height - h) * 0.5;
    [foreImage drawInRect: CGRectMake(x, y, w , h)];
    
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (UIImage *)pl_composeImageWithBackImage:(UIImage *)backImage foreImage:  (UIImage *)foreImage size:(CGFloat)sizeWH foreBorder:(CGFloat)border borderColor:(UIColor *)color {
    CGSize size = [backImage size];
    UIGraphicsBeginImageContext(size);
    
    [backImage drawInRect : CGRectMake(0, 0, size.width, size.height)];
    
    if (foreImage) {
        CGFloat w = sizeWH + 2 * border;
        CGFloat h = sizeWH + 2 * border;
        CGFloat x = (size.width - w) * 0.5;
        CGFloat y = (size.height - h) * 0.5;
        CGRect rect = CGRectMake(x, y, w , h);
        UIBezierPath* path = [UIBezierPath bezierPathWithRect:rect];
        [color set];
        [path fill];
        
        [foreImage drawInRect:CGRectMake(x + border, y + border, sizeWH, sizeWH)];
    }
    
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (UIImage *)pl_imageFromCIImage:(CIImage *)image size:(CGFloat)size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

//压缩图片
- (UIImage *)pl_imageScaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [self drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

+ (UIImage*)pl_imageNamed:(NSString *)name fromCustomBundleName:(NSString*)bundleName {
    if (name && bundleName) {
        NSString *bundlePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:bundleName];
        NSString *img_path = [bundlePath stringByAppendingPathComponent:name];
        return [UIImage imageWithContentsOfFile:img_path];
    }
    return nil;
}

+ (CGFloat)pl_comprogressImageQualityWithSize:(float)fileSize{
    CGFloat imgSizeKB = fileSize/1024.0;
    //根据图片大小设置图片质量系数
    CGFloat compressionQuality;
    if (imgSizeKB > 5*1014){
        compressionQuality = 0.02;
    }
    else if(imgSizeKB > 3*1014) { //大于3M
        compressionQuality = 0.03;
    } else if (imgSizeKB > 1.5*1024) {
        compressionQuality = 0.04;
    } else if (imgSizeKB > 0.5*1024) {
        compressionQuality = 0.1;
    } else {
        compressionQuality = 0.15;
    }
    compressionQuality = compressionQuality/5;
    return compressionQuality;
}

- (UIImage *)pl_fixOrientation{
    if (self.imageOrientation == UIImageOrientationUp) {
        return self;
    }
    
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    [self drawInRect:(CGRect){0, 0, self.size}];
    UIImage *fixedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return fixedImage;
}

+ (NSData *)pl_comprogressDataWithImage:(UIImage*)image {
    if (image) {
        CGFloat quality = [UIImage pl_comprogressImageQualityWithSize:300*1024.0];
        return UIImageJPEGRepresentation([image pl_fixOrientation], quality);
    }
    return nil;
}

+ (UIImage *)pl_image:(UIImage *)image rotation:(UIImageOrientation)orientation
{
    long double rotate = 0.0;
    CGRect rect;
    float translateX = 0;
    float translateY = 0;
    float scaleX = 1.0;
    float scaleY = 1.0;
    
    switch (orientation) {
        case UIImageOrientationLeft:
        rotate = M_PI_2;
        rect = CGRectMake(0, 0, image.size.height, image.size.width);
        translateX = 0;
        translateY = -rect.size.width;
        scaleY = rect.size.width/rect.size.height;
        scaleX = rect.size.height/rect.size.width;
        break;
        case UIImageOrientationRight:
        rotate = 3 * M_PI_2;
        rect = CGRectMake(0, 0, image.size.height, image.size.width);
        translateX = -rect.size.height;
        translateY = 0;
        scaleY = rect.size.width/rect.size.height;
        scaleX = rect.size.height/rect.size.width;
        break;
        case UIImageOrientationDown:
        rotate = M_PI;
        rect = CGRectMake(0, 0, image.size.width, image.size.height);
        translateX = -rect.size.width;
        translateY = -rect.size.height;
        break;
        default:
        rotate = 0.0;
        rect = CGRectMake(0, 0, image.size.width, image.size.height);
        translateX = 0;
        translateY = 0;
        break;
    }
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //做CTM变换
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    CGContextTranslateCTM(context, translateX, translateY);
    
    CGContextScaleCTM(context, scaleX, scaleY);
    //绘制图片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    
    return newPic;
}

@end
